export


TARGET=$(MAKECMDGOALS)# mean $(TARGET)==$(MAKECMDGOALS)
.PHONY:$(TARGET) hold



ifeq ($(PLATFORM),Linux)

ifeq ($($(TARGET)_TYPE),sharedlib)
assembler=g++
flag=-shared -o #
endif
ifeq ($($(TARGET)_TYPE),staticlib)
assembler=ar
flag= -r #
endif
ifeq ($($(TARGET)_TYPE),executebin)
assembler=g++
flag= -o #
endif

lib_path_spec:=-L

else

ifeq ($($(TARGET)_TYPE),sharedlib)
assembler=LINK
flag=/nologo /DLL /OUT:
endif
ifeq ($($(TARGET)_TYPE),staticlib)
assembler=LIB
flag=/nologo /OUT:
endif
ifeq ($($(TARGET)_TYPE),executebin)
assembler=LINK
flag=/nologo /OUT:
endif

lib_path_spec:=/LIBPATH:

endif



$(TARGET):$($(TARGET));# always run sub recipe, & recipe might not change sub, so here won't chg too
# check sub but just see the sub rst(sub file last modified time)

ifeq ($(PLATFORM),Linux)
define to_lib_ref
$(basename $(patsubst lib%,-l%,$(notdir $(1))))
endef

else

define to_lib_ref
$1
endef
ifeq ($($(TARGET)_TYPE),sharedlib)
define mid_file
$(patsubst %.dll,%.exp,$1)
endef
endif
endif

ifndef $(TARGET)_MAKEFILE
# xxx:$(TARGET1_FLAKE1) $(TARGET1_FLAKE2)
$($(TARGET)):$($(TARGET)_FLAKEs_VARs) $($(TARGET)_FLAKEs_LIBs)
ifeq ($(strip $($(TARGET)_FLAKEs_VARs)),)
	@echo no source or make rule for [$(notdir $@)]
else
	@# link part
ifeq ($($(TARGET)_TYPE),sharedlib)
ifneq ($(PLATFORM),Linux)
	@# when product dll in windows, if with .exp, then lib also need the related lib as when we call LINK
	@LIB /nologo /DEF /OUT:$(patsubst %.dll,%.lib,$@) $($(TARGET)_FLAKEs_VARs) $(addprefix $(lib_path_spec),$(PATH_LIB)) $(call to_lib_ref,$($(TARGET)_FLAKEs_LIBs))
endif
endif
	@$(assembler) $(flag)$@ $(call mid_file,$@) $($(TARGET)_FLAKEs_VARs) $(addprefix $(lib_path_spec),$(PATH_LIB)) $(call to_lib_ref,$($(TARGET)_FLAKEs_LIBs))
	@# {copy part|link part not bins{shared libs}}
	@echo [$(notdir $@)]
endif

$($(TARGET)_FLAKEs_LIBs):hold;

else
$($(TARGET)):hold
	@echo [$(notdir $($(TARGET)))] by $($(TARGET)_MAKEFILE)
	@-$(MAKE) -f $($(TARGET)_MAKEFILE)
endif


define manual_single_fresh
	@cat $1>$(addprefix .fresh,$1)
	@cat $(addprefix .fresh,$1)>$1
	@rm $(addprefix .fresh,$1)
endef

define get_index
$(words $(shell counter=;tick=;
	for var in $(2) ; do
		counter=$${counter}" a";
		if [ $(1) = $${var} ]; then
			tick=$${counter};
		fi
	done;
	echo $${tick}
))
endef

ifneq ($(strip $($(TARGET)_FLAKEs_VARs)),)
$($(TARGET)_FLAKEs_VARs):hold# as flake1: flake2: ...
ifeq ($($(TARGET)_FLAKE_set_updated),true)
	@$(call manual_single_fresh,$($(TARGET)_FLAKE$(call get_index,$@,$($(TARGET)_FLAKEs_VARs))_source))
endif
	@$(MAKE) $(call get_index,$@,$($(TARGET)_FLAKEs_VARs)) -s -f $(FILE_LOCATION)makefiles/FLAKE.mk
endif
hold:;
